package cn.hsw.component.auth.service.impl;

import cn.hsw.component.auth.constant.AuthConstant;
import cn.hsw.component.auth.jwt.JwtUtil;
import cn.hsw.component.auth.service.AuthService;
import cn.hsw.component.auth.vo.AuthUserVo;
import cn.hsw.component.core.util.BCrypt;
import cn.hsw.component.core.util.IdUtil;
import cn.hsw.component.core.util.Validator;
import cn.hsw.component.redis.RedisUtil;
import cn.hsw.manage.permission.service.PermissionService;
import cn.hsw.manage.role.service.RoleService;
import cn.hsw.manage.user.entity.User;
import cn.hsw.manage.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    UserService userService;
    @Autowired
    PermissionService permissionService;
    @Autowired
    RoleService roleService;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public String loginByPassword(String phone, String password) {
        /*校验*/
        Validator.validateNotEmpty(phone,AuthConstant.PHONE_NOT_EMPTY);
        Validator.validateNotEmpty(password,AuthConstant.PASSWORD_NOT_EMPTY);
        // 根据手机号查询用户
        User user = userService.selectUserByPhone(phone);
        Validator.validateNotEmpty(user,AuthConstant.USER_NOT_FOUND);
        /*密码校验*/
        Validator.checkpw(password,user.getPassword(),AuthConstant.PASSWORD_ERROR);
        /*通过调用登录*/
        String salt = BCrypt.hashpw(IdUtil.generate().toString(), BCrypt.gensalt());
        user.setSalt(salt);
        userService.edit(user);
        String token = JwtUtil.sign(phone,salt);
        /*@TODO 后续增加IP机器码，最大时间等信息*/
        redisUtil.set(AuthConstant.TOKEN_REDIS_KEY+token,"",AuthConstant.TOKEN_EXPIRE_TIME);
        JwtUtil.login(token);


        return token;
    }

    @Override
    public AuthUserVo getCurrUser() {

        User user = userService.selectUserByPhone(JwtUtil.getPhone());

        return AuthUserVo.builder()
                .pid(user.getPid())
                .userName(user.getUserName())
                .realName(user.getRealName())
                .phone(user.getPhone()).build();
    }

    @Override
    public Long getCurrUserPid() {
        return getCurrUser().getPid();
    }

    /*@Override
    public LoginUserVo getLoginUser() {

        // 获取当前登录用户
        User user = userService.selectUserByPhone(JwtUtils.getPhone());
        // 获取当前登录用户所有权限
        Set<String> permissionsSet = permissionService.getPermissionsSet(user.getPid());
        // 获取当前登录用户所有角色
        Set<String> roleSet = roleService.getRoleCodeSet(user.getPid());

        // @TODO 加缓存
        return LoginUserVo.builder()
                .user(user)
                .permissionsSet(permissionsSet)
                .roleSet(roleSet)
                .build();
    }*/
}
